<template>
    <view class="container">
        <!-- 聊天消息列表 -->
        <scroll-view 
            class="message-list" 
            scroll-y="true" 
            :scroll-top="scrollTop"
            :style="{height: windowHeight + 'px'}"
            @scrolltolower="loadMore">
            <view class="message-item" v-for="(item, index) in messages" :key="index">
                <view class="message-content" :class="item.isMe ? 'right' : 'left'">
                    <view class="avatar" :style="item.isMe ? 'margin-left: 10px;' : 'margin-right: 10px;'">
                        <text>{{ item.isMe ? '我' : '对方' }}</text>
                    </view>
                    <view class="bubble" :class="item.isMe ? 'bubble-right' : 'bubble-left'">
                        {{ item.content }}
                    </view>
                </view>
            </view>
            <!-- 滚动锚点 -->
            <view id="scroll-anchor" ref="anchor"></view>
        </scroll-view>

        <!-- 输入区域 -->
        <view class="input-area">
            <input 
                class="input-box" 
                v-model="inputValue" 
                placeholder="请输入消息..." 
                @confirm="sendMessage" />
            <button class="send-btn" @click="sendMessage">发送</button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            messages: [],
            inputValue: '',
            scrollTop: 0,
            windowHeight: 0,
            mockTimer: null
        }
    },
    onLoad() {
        // 获取窗口高度，减去输入区域高度得到消息列表高度
        uni.getSystemInfo({
            success: (res) => {
                this.windowHeight = res.windowHeight - 60; // 减去输入区域高度
            }
        });
        
        // 初始化一些测试消息
        this.initMockMessages();
    },
    onUnload() {
        // 清除定时器
        if(this.mockTimer) clearInterval(this.mockTimer);
    },
    watch: {
        // 监听消息数组变化，自动滚动到底部
        messages: {
            handler() {
                this.$nextTick(() => {
                    this.scrollToBottom();
                });
            },
            deep: true
        }
    },
    methods: {
        // 初始化模拟消息
        initMockMessages() {
            this.messages = [
                { isMe: false, content: "你好！" },
                { isMe: false, content: "这是一个自动滚动的聊天Demo。" },
                { isMe: false, content: "当有新消息时，会自动滚动到底部。" }
            ];
            
            // 模拟对方回复消息
            this.mockTimer = setInterval(() => {
                if(this.messages.length > 15) {
                    clearInterval(this.mockTimer);
                    return;
                }
                this.receiveMessage();
            }, 5000);
        },
        
        // 接收消息
        receiveMessage() {
            const replies = [
                "收到你的消息了",
                "正在查看...",
                "这个功能很实用",
                "自动滚动效果不错",
                "期待更多功能",
                "微信小程序也能正常使用",
                "测试一下长文本消息会怎样显示",
                "这条消息会自动滚动到底部吗？",
                "看来效果还不错",
                "希望能支持图片和表情"
            ];
            const randomIndex = Math.floor(Math.random() * replies.length);
            this.messages.push({
                isMe: false,
                content: replies[randomIndex]
            });
        },
        
        // 发送消息
        sendMessage() {
            if(!this.inputValue.trim()) return;
            
            this.messages.push({
                isMe: true,
                content: this.inputValue
            });
            
            this.inputValue = '';
        },
        
        // 滚动到底部
        scrollToBottom() {
            // 使用选择器获取滚动高度
            const query = uni.createSelectorQuery().in(this);
            query.select('#scroll-anchor').boundingClientRect(rect => {
                if (rect) {
                    // 设置滚动高度为锚点距离顶部的距离
                    this.scrollTop = rect.top;
                }
            }).exec();
        },
        
        // 加载更多历史消息
        loadMore() {
            // 模拟加载更多历史消息
            uni.showToast({
                title: '加载历史消息...',
                icon: 'none'
            });
        }
    }
}
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.message-list {
    flex: 1;
    padding: 15px;
    background-color: #f8f8f8;
}

.message-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;
}

.message-content.right {
    flex-direction: row-reverse;
    display: flex;
    align-items: flex-start;
    justify-content: flex-end;
}

.message-content.left {
    display: flex;
    align-items: flex-start;
}

.avatar {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background-color: #ccc;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #fff;
}

.bubble {
    max-width: 70%;
    padding: 10px 15px;
    border-radius: 18px;
    position: relative;
    font-size: 15px;
}

.bubble-left {
    background-color: #fff;
    color: #333;
}

.bubble-right {
    background-color: #07c160;
    color: #fff;
}

.input-area {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    border-top: 1px solid #eee;
    background-color: #fff;
}

.input-box {
    flex: 1;
    height: 40px;
    padding: 0 10px;
    border-radius: 20px;
    background-color: #f5f5f5;
    margin-right: 10px;
}

.send-btn {
    background-color: #07c160;
    color: #fff;
    border-radius: 20px;
    padding: 0 15px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    white-space: nowrap;
}
</style>    